<template>
  <el-select
    v-model="tempUserCode"
    remote
    filterable
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    :remote-method="remoteUserMethod"
    :loading="userLoading"
    :size="size"
  >
    <el-option
      v-for="item in userOptions"
      :key="item.userCode"
      :label="`${item.userCode}/${item.userName}`"
      :value="item.userCode"
    />
  </el-select>
</template>

<script>
import { fetchUserArray } from '@/api/base/common'

export default {
  name: 'BaseUserSelect',
  props: {
    // 父组件传来的值
    placeholder: {
      type: String,
      default: '',
      require: false
    },
    disabled: {
      type: Boolean,
      default: false,
      require: false
    },
    clearable: {
      type: Boolean,
      default: false,
      require: false
    },
    value: {
      type: String,
      default: '',
      require: false
    },
    size: {
      type: String,
      default: '',
      require: false
    },
    orgCode: {
      type: String,
      default: '',
      require: false
    }
  },
  data() {
    return {
      currentUserCode: '',
      userOptions: [],
      userLoading: false
    }
  },
  computed: {
    tempUserCode: {
      get() {
        return this.currentUserCode
      },
      set(newVal) {
        const oldVal = this.currentUserCode
        this.currentUserCode = newVal
        this.$emit('input', newVal)
        this.$emit('change', newVal, oldVal)
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        if (this.currentUserCode === value) {
          return
        }
        this.currentUserCode = value
      }
    }
  },
  created() {
    this.remoteUserMethod('')
  },
  methods: {
    remoteUserMethod(query) {
      query = query == null ? '' : query.trim()
      this.userLoading = true
      fetchUserArray(query, this.orgCode).then((response) => {
        this.userOptions = response.data
        this.userLoading = false
      }, (response) => {
        this.userLoading = false
      })
    }
  }
}
</script>
